package com.it.service.impl;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.google.code.kaptcha.Producer;
import com.it.entity.SysUser;
import com.it.service.AuthService;
import com.it.utisl.RedisUtil;
import com.it.vo.Const;
import com.it.vo.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;

/**
 * TODO
 *
 * @author: Coke
 * @DateTime: 2023/11/19/14:26
 **/
@Slf4j
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private Producer producer;

    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Autowired
    private RedisUtil redisUtil;
    
    /**
     * 生成验证码
     * @DateTime: 2023/11/19 14:28
     *
     * @param request:
     * @param response:
     * @return Response<?>
     * @author: Coke
     */
    @Override
    public Response<?> captcha (HttpServletRequest request, HttpServletResponse response) {
        // 生成验证码文本
        String code = producer.createText();
        // 生成一个随机的key
        String key = UUID.randomUUID().toString();
    
        // 生成验证码图片
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            // 将验证码图片写入输出流
            ImageIO.write(image, "jpg", outputStream);
        
            // 将输出流中的图片转换为Base64编码的字符串
            BASE64Encoder base64Encoder = new BASE64Encoder();
            String str = "data:image/jpeg;base64,";
            String base64Img = str + base64Encoder.encode(outputStream.toByteArray());
        
            // 将验证码和key存入Redis，并设置过期时间为120秒
            redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);
        
            // 打印验证码和对应的key到日志中
            log.info("验证码 -- {} - {}", key, code);
        
            // 构建返回的Map对象
            Map<Object, Object> map = MapUtil.builder().put("key", key)
                  .put("base64Img", base64Img).build();
        
            // 返回成功响应，携带验证码的key和Base64编码的图片
            return Response.ok(map);
        } catch (IOException e) {
            // 捕获IO异常，返回错误响应
            e.printStackTrace();
            return Response.error("验证码生成异常," + e.getMessage());
        }
    }

    @Override
    public Response<?> login(SysUser sysUser) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysUser.getUsername(), sysUser.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (ObjectUtil.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误！");
        }
        return Response.ok("登录成功！");
    }
}
